<?php

namespace App\Http\Models;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    //set  tableName
    protected $table = 'category';
    //set   primaryKey
    protected $primaryKey = 'cate_id';
    //设置不自动维护
    public $timestamps = false;

    //数据填充黑名单
    protected $guarded = [];
    /**
     * @param $data --数据
     * @param $id --分类id
     * @param $pid --分类上级id
     * @param int $pid_value --顶级id 默认0
     * @return array --处理好的分类
     */
    protected static function getTree($data,$id,$pid,$pid_value=0){
        $new_data = array();
        foreach($data as $key=>$value){
            if($value->$pid == $pid_value){
                $value->_cate_name = $value->cate_name;
                unset($data[$key]);
                $new_data[] = $value;
                foreach($data as $k=>$v){
                    if($v->$pid == $value->$id){
                        $v->_cate_name = '----'.$v->cate_name;
                        unset($data[$k]);
                        $new_data[] = $v;
                    }
                }
            }
        }
        return $new_data;
    }

    /**
     * @return mixed 获取分类信息 按order 升序
     */
    public static function tree(){
        $data = self::orderBy('cate_order','asc')->get();
        return self::getTree($data,'cate_id','cate_pid',0);
    }
}
